/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif
namespace Oceanside
{
    static class CheckHistoryBindings
    {
        static int listPageScrollIndex = 0;
        private const int CONST_LINE_ITEMS_PER_VIEW = 12;

        public static ORDER SelectedOrder
        {
            get;
            set;
        }


        /// <summary>
        /// 
        /// </summary>
        public static void Init()
        {
            ///Handler for the cancel button
            CheckHistoryWindow.ExitButton.MouseDown += new MouseButtonEventHandler(cancelButton_MouseDown_NOTHROW);
            CheckHistoryWindow.ScrollUpButton.ShineButtonClicked += new RoutedEventHandler(upButton_ShineButtonClicked_NOTHROW);
            CheckHistoryWindow.ScrollDownButton.ShineButtonClicked += new RoutedEventHandler(downButton_ShineButtonClicked_NOTHROW);

            CheckHistoryWindow.FilterByDateButton.ButtonDownDelegate +=
                new Oceanside.Button_95_50_FilterView.FunctionButtonDownDelegate(bFilterByDay_Click_NOTHROW);
            CheckHistoryWindow.FilterClosedTablesButton.ButtonDownDelegate +=
                new Oceanside.Button_95_50_FilterView.FunctionButtonDownDelegate(bFilterClosed_Click_NOTHROW);
            CheckHistoryWindow.FilterOpenTablesButton.ButtonDownDelegate +=
                new Oceanside.Button_95_50_FilterView.FunctionButtonDownDelegate(bFilterOpen_Click_NOTHROW);
            CheckHistoryWindow.FilterAllButton.ButtonDownDelegate +=
                new Oceanside.Button_95_50_FilterView.FunctionButtonDownDelegate(bFilterAll_Click_NOTHROW);
            CheckHistoryWindow.FilterByUserButton.ButtonDownDelegate +=
                new Button_95_50_FilterView.FunctionButtonDownDelegate(bFilterByUser_Click_NOTHROW);

            CheckHistoryWindow.PaymentsListView.SelectionChanged +=
                new SelectionChangedEventHandler(OrdersListView_SelectionChanged);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param Name="sender"></param>
        /// <param Name="e"></param>
        static void downButton_ShineButtonClicked_NOTHROW(object sender, RoutedEventArgs e)
        {
            try
            {
                ListScrollClicked(false);
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_LVBBIND_SCROLL_DOWN, exc);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public static void PrepareForScreenChange_NOTHROW()
        {
            try
            {
                SelectedOrder = null;
                Oceanside.Button_95_50_FilterView.UnHilightAll();
                CheckHistoryWindow.PaymentsListView.ItemsSource = null;
                CheckHistoryWindow.AssignDataContext(SHIFT.Current);
                Refresh();
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_LVBBIND_PREPARE_FOR_SCREEN_CHANGE, exc);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param Name="sender"></param>
        /// <param Name="e"></param>
        static void upButton_ShineButtonClicked_NOTHROW(object sender, RoutedEventArgs e)
        {
            try
            {
                ListScrollClicked(true);
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_LVBBIND_SCROLL_UP, exc);
            }
        }

        /// <summary>
        /// Scrolls the customers ticket up and down.
        /// </summary>
        /// <param Name="directionUp"></param>
        static void ListScrollClicked(bool directionUp)
        {
            if (directionUp)
            {
                listPageScrollIndex -= CONST_LINE_ITEMS_PER_VIEW;

                ///Since we just went ahead and knocked off an entire view panels worth, we
                ///need to assure we didn't drive negative.
                if (listPageScrollIndex < 0)
                {
                    listPageScrollIndex = 0;
                }
            }
            else  ///Must be scroll down
            {
                listPageScrollIndex += CONST_LINE_ITEMS_PER_VIEW;

                ///Make sure we didn't go too far, correct if we did by placing the view 
                ///at the end.
                if (listPageScrollIndex >= CheckHistoryWindow.PaymentsListView.Items.Count)
                {
                    listPageScrollIndex = CheckHistoryWindow.PaymentsListView.Items.Count - 1;
                }
            }
            UpdateTicketFocus();
        }

        /// <summary>
        /// Should be called whenever we delete an item from the customer ticket or
        /// add or scroll items.
        /// </summary>
        static void UpdateTicketFocus()
        {
            ///Sanity bounds customerCheck even though it is done elsewhere often.
            if ((listPageScrollIndex >= 0) && (listPageScrollIndex < CheckHistoryWindow.PaymentsListView.Items.Count))
            {
                if (CheckHistoryWindow.PaymentsListView.Items != null && CheckHistoryWindow.PaymentsListView.Items.Count != 0)
                {
                    CheckHistoryWindow.PaymentsListView.ScrollIntoView(CheckHistoryWindow.PaymentsListView.Items[listPageScrollIndex]);
                    ///Select the new item we just put focus on.
                    CheckHistoryWindow.PaymentsListView.SelectedItem = CheckHistoryWindow.PaymentsListView.Items[listPageScrollIndex];
                }
            }
            else
            {
                ///If we jump out of bounds then just set the index to zero.
                listPageScrollIndex = 0;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param Name="sender"></param>
        /// <param Name="e"></param>
        static void cancelButton_MouseDown_NOTHROW(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
            try
            {
                SelectedOrder = null;
                ControlPanelWindow.Show();
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_LVBBIND_CANCEL_BUTTON_MOUSE_DOWN, exc);
            }
        }
        /// <summary>
        /// Update the selected payment as the user clicks through them.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void OrdersListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            e.Handled = true;

            if (e.AddedItems.Count != 0)
            {
                SelectedOrder = e.AddedItems[0] as ORDER;
                Refresh();
            }
        }

        /// <summary>
        /// Assure the GUI displays properly.  This will update the visibility of buttons and etc.
        /// </summary>
        public static void Refresh()
        {
            PosWindow.RefreshVisibility(PosWindow.PROP_TYPE_ENUM.OH);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dontcare"></param>
        static void bFilterClosed_Click_NOTHROW(int dontcare)
        {
            try
            {
                SelectedOrder = null;
                BUSINESS_DAY bd = BUSINESS_DAY.GetNow(SHIFT.GlobalContext);
                if (SHIFT.Current.UserCanSeeOtherUsersOrders())
                {
                    CheckHistoryWindow.PaymentsListView.ItemsSource =
    SHIFT.GlobalContext.ORDERS.Where(o => o.BusinessDayId == bd.Id && o.IsClosed).AsEnumerable();
                }
                else
                {
                    CheckHistoryWindow.PaymentsListView.ItemsSource =
    SHIFT.GlobalContext.ORDERS.Where(o => o.BusinessDayId == bd.Id && o.IsClosed && o.UserId == SHIFT.Current.User.Id).AsEnumerable();
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_PLACEHOLDER, exc);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dontcare"></param>
        static void bFilterOpen_Click_NOTHROW(int dontcare)
        {
            try
            {
                SelectedOrder = null;
                BUSINESS_DAY bd = BUSINESS_DAY.GetNow(SHIFT.GlobalContext);
                if (SHIFT.Current.UserCanSeeOtherUsersOrders())
                {
                    CheckHistoryWindow.PaymentsListView.ItemsSource =
    SHIFT.GlobalContext.ORDERS.Where(o => o.BusinessDayId == bd.Id && !o.IsClosed).AsEnumerable();
                }
                else
                {
                    CheckHistoryWindow.PaymentsListView.ItemsSource =
    SHIFT.GlobalContext.ORDERS.Where(o => o.BusinessDayId == bd.Id && !o.IsClosed && o.UserId == SHIFT.Current.User.Id).AsEnumerable();
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_PLACEHOLDER, exc);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dontcare"></param>
        static void bFilterByUser_Click_NOTHROW(int dontcare)
        {
            try
            {
                Oceanside.FullKeyboard.ActiveKeyboard.SetSmallMode(false);
                Oceanside.FullKeyboard.ActiveKeyboard.SetMessage("Enter the USERID:");
                Oceanside.FullKeyboard.ActiveKeyboard.ShowMe();

                if (Oceanside.FullKeyboard.LastResponse == UserResponse.ENTER)
                {
                    if (Oceanside.FullKeyboard.GuiKeyPressedString != null)
                    {
                        try
                        {
                            string userName = Oceanside.FullKeyboard.GuiKeyPressedString;
                            var q = SHIFT.GlobalContext.USERS.Where(u => u.UserName == userName);
                            if (q.Any())
                            {
                                USER user = q.First();
                                BUSINESS_DAY bd = BUSINESS_DAY.GetNow(SHIFT.GlobalContext);
                                var orderQ = SHIFT.GlobalContext.ORDERS.Where(o => o.BusinessDayId == bd.Id && o.UserId == user.Id);

                                if (orderQ.Any())
                                {
                                    CheckHistoryWindow.PaymentsListView.ItemsSource = orderQ.ToList();
                                }
                                else
                                {
                                    CheckHistoryWindow.PaymentsListView.ItemsSource = null;
                                }
                            }
                        }
                        catch
                        {
                            UMD.ShowGuiMessageSTASafe_NOTHROW("You have entered an invalid USERID id.");
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_LVBBIND_FILTER_ALL, exc);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dontcare"></param>
        static void bFilterAll_Click_NOTHROW(int dontcare)
        {
            try
            {
                SelectedOrder = null;
                BUSINESS_DAY bd = BUSINESS_DAY.GetNow(SHIFT.GlobalContext);
                if (SHIFT.Current.UserCanSeeOtherUsersOrders())
                {
                    CheckHistoryWindow.PaymentsListView.ItemsSource =
    SHIFT.GlobalContext.ORDERS.Where(o => o.BusinessDayId == bd.Id).AsEnumerable();
                }
                else
                {
                    CheckHistoryWindow.PaymentsListView.ItemsSource =
    SHIFT.GlobalContext.ORDERS.Where(o => o.BusinessDayId == bd.Id && o.UserId == SHIFT.Current.User.Id).AsEnumerable();
                }
            }
            catch (Exception e)
            {
                Logging.LogException(e);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dontcare"></param>
        static void bFilterByDay_Click_NOTHROW(int dontcare)
        {
            try
            {

            }
            catch (Exception exc)
            {
                App.InvokeStopStoryBoard_NOTHROW();
                Constants.ErrorDispatcher.Notify(Error.EType.E_LVBBIND_FILTER_AUTHS, exc);
            }
        }
    }
}
